<template>
  <f7-page ptr @ptr:refresh="refresh" infinite :infinite-preloader="true" @infinite="infinite">
    <!-- <f7-navbar>
      <f7-nav-left>
        <f7-link back icon-material="arrow_back"></f7-link>
      </f7-nav-left>
      <f7-nav-title>已绑定应用</f7-nav-title>
      <f7-nav-right>
        <f7-link @click="$refs.actionsGroup.open()">新增</f7-link>
      </f7-nav-right>
    </f7-navbar> -->
    <qm-currentcy-navbar title="已绑定应用">
      <template #nav-right>
        <f7-link @click="$refs.actionsGroup.open()" style="padding: 0; color: #000; min-width: auto;">新增</f7-link>
      </template>
    </qm-currentcy-navbar>
    <f7-list-fund :parent="this" message="向左边滑动解绑设备">
      <f7-list media-list>
        <f7-list-item
          swipeout
          v-for="item in query.data"
          :key="item.oauthId"
          :title="item.createdUserName"
          :after="item.createdDate | date"
          :subtitle="item.oauthType | prefix('第三方应用：')"
        >
          <f7-swipeout-actions right>
            <f7-swipeout-button close color="red" @click="unbind(item)">解绑</f7-swipeout-button>
          </f7-swipeout-actions>
        </f7-list-item>
      </f7-list>
    </f7-list-fund>
    <f7-list-nofund :parent="this"></f7-list-nofund>

    <f7-actions ref="actionsGroup">
      <f7-actions-group>
        <f7-actions-label>增加第三方授权</f7-actions-label>
        <f7-actions-button @click="addWeixin">微信</f7-actions-button>
        <f7-actions-button color="red">取消</f7-actions-button>
      </f7-actions-group>
    </f7-actions>
  </f7-page>
</template>
<script>
import controller from "@/libs/framework/controller";
import Config from "@/libs/config";

export default class instance extends controller {
  onBeforeInit() {
    this.urls.query = "/api/app/appSetting/queryOauth";
  }
  onInit() {
    this.setSearch("appCode", Config.info.id);
    this.setSearch("userId", vue.$f7.data.currentUser.userId);
  }
  
  mixin() {
    return {
      methods: {
        addWeixin() {
          let self = this;
          if (!window.plus) {
            self.$f7.dialog.alert("不是手机端无法使用微信授权!");
            return;
          }
          plus.oauth.getServices(
            function(services) {
              let auths = services;
              for (var i in services) {
                let service = services[i];
                auths[service.id] = service;
              }
              let aweixin = auths["weixin"];
              if (!aweixin) {
                plus.nativeUI.alert("当前环境不支持微信登录");
                return;
              }

              new Promise((rs, rj) => {
                if (!aweixin.authResult) {
                  aweixin.authorize(
                    function(e) {
                      console.log("授权码：", e.code); //app端获取到的code

                      aweixin.login(
                        function(e) {
                          rs(e.target);
                        },
                        function(e) {
                          rj(new Error("登录认证失败: " + JSON.stringify(e)));
                        }
                      );
                    },
                    function(e) {
                      plus.nativeUI.alert("授权失败：" + JSON.stringify(e));
                      rj(new Error("微信授权失败"));
                    },
                    {
                      scope: "snsapi_userinfo",
                      state: "authorize test"
                      // appid: 'wx89a21ed838ea321b'
                    }
                  );
                } else {
                  rs(aweixin);
                }
              })
                .then(rlt => {
                  let params = {
                    oauthType: "WEIXIN",
                    openId: rlt.authResult.openid,
                    accessToken: rlt.authResult.access_token
                  };
                  self.$f7.request.postJSON(
                    "/api/app/appSetting/bindOauth",
                    { model: params, appCode: Config.info.id },
                    r => {
                      if (r && r.success) {
                        self.$f7.dialog.toast("添加成功");
                        self.getViewModel();
                      } else {
                        self.$f7.dialog.alert(
                          r.message || "添加失败，请稍后重试"
                        );
                      }
                    }
                  );
                })
                .catch(err => {
                  plus.nativeUI.alert(err);
                });
            },
            function(e) {
              plus.nativeUI.alert(
                "获取登录授权服务列表失败：" + JSON.stringify(e)
              );
            }
          );
        },
        unbind(item) {
          let self = this;
          self.$f7.dialog.confirm("确定解绑该设备嘛？", () => {
            self.$f7.request.postJSON(
              "/api/app/appSetting/unbindOauth",
              { oauthId: item.oauthId },
              r => {
                if (r && r.success) {
                  self.$f7.dialog.toast("解绑成功");
                  if (item.oauthType == 'WEIXIN') {
                    self.weixinLogout();
                  }
                  self.getViewModel();
                } else {
                  self.$f7.dialog.alert(r.message || "解绑失败，请稍后重试");
                }
              }
            );
          });
        },
        weixinLogout() {
          plus.oauth.getServices(function(services) {
            let auths = services;
            for (var i in services) {
              let service = services[i];
              auths[service.id] = service;
            }
            let aweixin = auths["weixin"];
            if (!aweixin) {
              plus.nativeUI.alert("当前环境不支持微信登录");
              return;
            }

            aweixin.logout(
              function(e) {
                plus.nativeUI.alert("注销登录认证成功!");
              },
              function(e) {
                plus.nativeUI.alert("注销登录认证失败: " + JSON.stringify(e));
              }
            );
          });
        }
      }
    };
  }
}
</script>

<style lang="less" scoped>
::v-deep .page-content {
  padding-top: calc(88px * var(--ratio))
}
</style>
